package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/23 17:27
 */
@Component
public class StorageTccActionImpl implements StorageTccAction {

    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, Long productId, Integer count) {
        Storage storage = storageMapper.selectByProductId(productId);
        if (storage.getResidue().compareTo(count) < 0) {
//            return true; // 返回false, 第二阶段代码仍会执行
            throw new RuntimeException("库存不足");
        }
        storageMapper.updateResidueToFrozen(productId, count);
        // 保存一阶段的成功标记
        ResultHolder.setResult(StorageTccAction.class, businessActionContext.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext businessActionContext) {
        // 二阶段检查标记是否存在, 不存在则不再执行二阶段代码
        //      1.二阶段已经执行过;
        //      2.一阶段失败;
        if (ResultHolder.getResult(StorageTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }
        Long productId = Long.valueOf(businessActionContext.getActionContext("productId").toString());
        Integer count = Integer.valueOf(businessActionContext.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId, count);
        // 二阶段执行完成, 删除标记
        ResultHolder.removeResult(StorageTccAction.class, businessActionContext.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(StorageTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }
        Long productId = Long.valueOf(businessActionContext.getActionContext("productId").toString());
        Integer count = Integer.valueOf(businessActionContext.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, businessActionContext.getXid());
        return true;
    }
}
